import * as db from './common.js'
//后台路径
const apiBaseUrl = 'https://hz-longmen.aiairy.com/ipark/api'
//const apiBaseUrl = '/sn-api/ipark/api'
//const apiBaseUrl = 'http://47.94.255.121/sn-chart-api/ipark/api'
import {
	request
} from '@/api/request.js/'
const post = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header = {
		'Accept': 'application/json',
		'Content-Type': 'application/json',
		// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
	}
	if (method.indexOf('/mini/login') == -1) {
		header = setHeader(header);
	}
	return request({
		url: apiBaseUrl + method,
		data: data,
		header: header,
		method: 'POST'
	});
}

const get = (method, data) => {
	var header = {
		'Accept': 'application/json',
		'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
	}
	if (data && !db.isEmpty(data.token)) {
		header['Authorization'] = 'Bearer ' + data.token
		delete data["token"]
	} else {
		header = setHeader(header)
	}
	return request({
		url: apiBaseUrl + method,
		data: data,
		header: header,
		method: 'GET'
	});
}

const setHeader = header => {
	let userToken = db.get("token");
	if (userToken) {
		header['Authorization'] = 'Bearer ' + db.get('token') // 让每个请求携带自定义 token 请根据实际情况自行修改
	}
	return header
}

//put
const put = (method, data) => {
	uni.showLoading({
		title: '加载中'
	});
	var header = {
		'Accept': 'application/json',
		'Content-Type': 'application/json',
	}
	header = setHeader(header);

	return request({
		url: apiBaseUrl + method,
		data: data,
		header: header,
		method: 'PUT'
	});

}
// 普通上传图片
export const uploadImage = (num, callback) => {
	var header = {
		'Accept': 'application/json',
		'Content-Type': 'multipart/form-data',
		// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
	}
	header = setHeader(header);
	uni.chooseImage({
		count: num,
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++) {
				uni.uploadFile({
					url: apiBaseUrl + '/web-api' + '/sys/common/upload',
					filePath: tempFilePaths[i],
					fileType: 'image',
					name: 'file',
					header: header,
					formData: {
						'method': 'images.upload',
						'upfile': tempFilePaths[i]
					},
					success: (uploadFileRes) => {
						callback();
					},
					fail: (error) => {
						if (error && error.response) {
							showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					},
				});
			}
		}
	});
}

function convertParams(params) {
	let url = ""
	let index = 0
	for(let item in params){
		let str = index == 0 ? "?" : "&";
		url = url + str + item + '=' + params[item]
		index++;
	}
	return url
}

export {
	post,
	get,
	put,
	convertParams
}
